import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { WithAuth } from "../lib/authutils";
import { FormSkeleton } from '../components/skeletons'
import { ModalErrorMessage, StyleLabel } from '../lib/formstyles'
import { RenderProjectVulnerability } from '../lib/data/api';
interface VulnerabilityRenderProps {
  action: string;
}

const VulnerabilityRender: React.FC<VulnerabilityRenderProps> = ({ action }) => {
  const { id, projectId } = useParams<{ id: string; projectId: string }>(); // Access route parameters
  const navigate = useNavigate(); // Add navigate function
  const [htmlContent, setHtmlContent] = useState<string | null>(null);
  const [loadingError, setLoadingError] = useState(false)
  const [loading, setLoading] = useState(true)

  const handleBack = () => {
    navigate(-1); // Navigate back to previous page
  };

  useEffect(() => {
    const cssUrl = "/static/css/report-vulnerability-details.css";

    const fetchData = async () => {
      try {
        const html = await RenderProjectVulnerability(id);
        setHtmlContent(html);
        setLoadingError(false);

        // Inject CSS dynamically
        if (!document.getElementById("dynamic-css-report")) {
          const link = document.createElement("link");
          link.rel = "stylesheet";
          link.href = cssUrl;
          link.type = "text/css";
          link.id = "dynamic-css-report";
          document.head.appendChild(link);
        }

        if (!document.getElementById("dynamic-css-overrides")) {
          const style = document.createElement("style");
          style.id = "dynamic-css-overrides";
          style.innerHTML = `
          .vulnerability-render-container {
            border: 1px solid #ddd;
            padding: 10px;
            border-radius: 5px;
            background: white;
            color: black;
            max-height: 900px;
          }

          .vulnerability-render-container body,
          .vulnerability-render-container div,
          .vulnerability-render-container span,
          .vulnerability-render-container p,
          .vulnerability-render-container h1,
          .vulnerability-render-container h2,
          .vulnerability-render-container h3,
          .vulnerability-render-container h4,
          .vulnerability-render-container h5,
          .vulnerability-render-container h6 {
            margin: 0 !important;
            padding: 0 !important;
            line-height: 1.5 !important;
            word-wrap: break-word;
          }

          /* Add margin to heading tags inside the container */
          .vulnerability-render-container h1,
          .vulnerability-render-container h2,
          .vulnerability-render-container h3,
          .vulnerability-render-container h4,
          .vulnerability-render-container h5,
          .vulnerability-render-container h6 {
            margin: 10px 0 !important;
          }

          /* Scoped img styling for the container */
          .vulnerability-render-container img {
            width: 40% !important;
            height: auto;
            display: block;
          }
        `;
          document.head.appendChild(style);
        }
      } catch (err) {
        setLoadingError(false);
      }
      finally {
        setLoading(false);
      }
    };

    fetchData();

    return () => {
      // Cleanup dynamic CSS
      const existingLink = document.getElementById("dynamic-css-report");
      const existingStyle = document.getElementById("dynamic-css-overrides");
      if (existingLink) existingLink.remove();
      if (existingStyle) existingStyle.remove();
    };
  }, [projectId, id]); // Dependencies include projectId and id

 if (loadingError) return <ModalErrorMessage message={"Error loading vulnerability"} />
  if(loading) return <FormSkeleton numInputs={6} className='max-w-lg'/>
  return (
    <div className="w-full flex-1 rounded-lg min-h-[800px] border-black relative">
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-2xl">Vulnerability Report</h1>
        <button 
          onClick={handleBack}
          className="px-4 py-2 bg-gray-200 hover:bg-gray-300 rounded-md flex items-center transition-colors"
        >
          <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
          </svg>
          Back
        </button>
      </div>
      <div className="vulnerability-render-container overflow-y-scroll">
        <div className="overflow-y-scroll" dangerouslySetInnerHTML={{ __html: htmlContent || "" }} />
      </div>
    </div>
  );
};

export default WithAuth(VulnerabilityRender);
